package com.zhu.bitcom.controller;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.wf.captcha.GifCaptcha;
import com.zhu.bitcom.pojo.UserInfo;
import com.zhu.bitcom.pojo.VO.LoginVo;
import com.zhu.bitcom.pojo.VO.RegisterVo;
import com.zhu.bitcom.service.IUserInfoService;
import com.zhu.bitcom.utils.CaptchaUtil;
import com.zhu.bitcom.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@RestController
@RequestMapping("/user")
public class LoginAndRegisterController {

    @Autowired
    private IUserInfoService userInfoService;

    @RequestMapping("/test")
    public void test(HttpServletRequest request, HttpServletResponse response) throws IOException {
        CaptchaUtil.out(request, response);
        //return Result.ok(userId);
    }

    @PostMapping("/login")
    public Result<SaTokenInfo> login(@RequestBody(required = false) LoginVo loginVo) {
        return userInfoService.userLogin(loginVo);
    }

    @PostMapping("/register")
    public Result<String> register(@RequestBody(required = false) RegisterVo registerVo) {
        return userInfoService.userRegister(registerVo);
    }

    /**
     * 登出
     *
     * @return
     */
    @RequestMapping("/logout")
    public Result logout() {
        StpUtil.logoutByTokenValue(StpUtil.getTokenValue());
        return Result.ok();
    }

    @RequestMapping("/isLogin")
    public String isLogin() {
        return "当前会话是否登录：" + StpUtil.isLogin();
    }

    @GetMapping("/info")
    public Result<UserInfo> getUserInfo() {
        return userInfoService.getUserInfo();
    }

    @GetMapping("/captcha")
    public void getCaptcha(HttpServletRequest request, HttpServletResponse response) {
        try {
            GifCaptcha gifCaptcha = new GifCaptcha(130, 48, 4);
            gifCaptcha.out(response.getOutputStream());
            String text = gifCaptcha.text().toLowerCase();
            log.info(text);
            request.getSession().setAttribute("CAPTCHA", text);
        } catch (Exception e) {
            log.info("验证码出粗错了：{}", e.getMessage());
        }
    }
}
